from django.shortcuts import render
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.http import HttpResponseRedirect
from django.contrib.auth import get_user_model, authenticate
from django.contrib.auth.decorators import login_required

Student = get_user_model()  # 学生对象

from course.models import *
from students.forms import UserRegisterForm


# Create your views here.


# setting 里要有对应的配置 AUTHENTICATION_BACKENDS
class CustomBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            # 让学生使用 姓名、学号登录、邮箱 登录
            # student = Student.objects.get(Q(email=username) | Q(username=username) | Q(uid=username))
            if username.isdigit():
                student = Student.objects.get(Q(uid=username))
            else:
                student = Student.objects.get(Q(username=username) | Q(email=username))
            if student.check_password(password):
                return student
        except Exception as e:
            return None


def register_view(request):
    """
    注册页
    :param request:
    :return:
    """
    if request.method == "POST" and request.POST:
        form = UserRegisterForm(request.POST)
        # print(form)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password1']
            user = Student(
                username=username,
            )
            user.set_password(password)
            user.uid = Student.objects.all().order_by("id").last().uid + 1
            user.save()
            return render(request, 'register_success.html', locals())
    else:
        form = UserRegisterForm()
    return render(request, "register.html", locals())


def login_view(request):
    """
    登录页
    :param request:
    :return:
    """
    if request.method == "POST" and request.POST:
        username = request.POST.get("username", None)
        passoword = request.POST.get("password", None)
        if username and passoword:
            try:
                if username.isdigit():
                    student = Student.objects.filter(is_staff=False).get(Q(uid=username))
                else:
                    student = Student.objects.filter(is_staff=False).get(Q(username=username) | Q(email=username))
                if student.check_password(passoword):
                    request.session['is_login'] = True
                    request.session['user_uid'] = student.uid
                    request.session['username'] = student.username
                    return HttpResponseRedirect("/score")
                else:
                    passoword_error = "密码错误"
            except Exception as e:
                username_error = "用户不存在"

    return render(request, "login.html", locals())


def logout_view(request):
    """
    登出页
    :param request:
    :return:
    """
    if not request.session.get('is_login', None):
        # 如果本来就未登录，也就没有登出一说
        return HttpResponseRedirect("/")
    request.session.flush()
    # 或者使用下面的方法删除 session
    # del request.session['is_login']
    # del request.session['user_uid]
    # del request.session['username']
    return HttpResponseRedirect("/")


# @login_required(login_url="/")
def student_course(request):
    """
    学生课程成绩
    :param request:
    :return:
    """
    user_id = request.session.get('user_uid', None)
    session_key = request.session.session_key  # 获取 session_key，跟浏览器的一样
    # print(user_id)
    if user_id:
        courses_score = StudentCourse.objects.filter(student__uid=user_id).order_by("-id")
        # print(courses_score)
    else:
        return HttpResponseRedirect("/")
    return render(request, "course.html", locals())
